import Vue from 'vue'
import Vuex from 'vuex'

import {getTodoList,setTodoList} from './storage'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    todoList: getTodoList(),
    showType: 1,
    loading: false
  },
  mutations: {
    // 标记是否已完成
    changeItem(state,id) {
      state.todoList.some(v => {
        if(v.id === id) {
          v.finished = !v.finished
          return true
        }
        return false
      })
      setTodoList(state.todoList)
    },
    // 添加事项
    addItem(state,item) {
      state.todoList = [item,...state.todoList]
      setTodoList(state.todoList)
    },
    // 删除事项
    deleteItem(state,id) {
      state.todoList.some((v,i) => {
        if(v.id === id) {
          state.todoList.splice(i,1)
          return true
        }
        return false
      })
      setTodoList(state.todoList)
    },
    // 修改显示状态
    changeShowType(state,type) {
      state.showType = type
    },
    // 清除已完成事项
    deleteFinishedTodoList(state) {
      state.todoList = state.todoList.filter(v => !v.finished)
      setTodoList(state.todoList)
    },
    // 修改loading状态
    changeLoading(state) {
      state.loading = !state.loading
    }
  },
  actions: {
    // 异步清除已完成事项
    deleteFinishedTodoListAsync(context) {
      context.commit('changeLoading')
      setTimeout(() => {
        context.commit('deleteFinishedTodoList')
        context.commit('changeLoading')
      },3000)
    }
  },
  modules: {
  },
  getters: {
    showTodoList: state => {
      switch (state.showType) {
        case 1: 
          return JSON.parse(JSON.stringify(state.todoList))
        case 2:
          return JSON.parse(JSON.stringify(state.todoList.filter(v => !v.finished)))
        case 3:
          return JSON.parse(JSON.stringify(state.todoList.filter(v => v.finished)))
      }
    },
    todoListCount: state => {
      switch (state.showType) {
        case 1: 
          return state.todoList.length
        case 2:
          return state.todoList.filter(v => !v.finished).length
        case 3:
          return state.todoList.filter(v => v.finished).length
      }
    },
    finishedCount: state => state.todoList.filter(v => v.finished).length
  }
})
